package com.springboot.jwt.web;

import com.springboot.jwt.common.JWTToken;
import com.springboot.jwt.common.JWTUtils;
import com.springboot.jwt.common.Result;
import com.springboot.jwt.common.ResultUtils;
import com.springboot.jwt.dto.UserDTO;
import com.springboot.jwt.exception.BizException;
import com.springboot.jwt.pojo.User;
import com.springboot.jwt.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Date;

/**
 * @Author: Jyf
 * @Date: 2020/12/17 9:26
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    UserService userService;

    @PostMapping("/login")
    public Result login(@Valid UserDTO user) {
        String username = user.getUsername();
        String password = user.getPassword();

        User us = userService.findByUsername(username);
        if (us == null) {
            throw new BizException("用户不存在");
        }
        String salt = us.getSalt();
        Md5Hash md5Hash = new Md5Hash(password, salt, 100);
        //生成token
        String token = JWTUtils.sign(username, md5Hash.toHex());
        //执行登入：（出现异常被全局异常捕捉）
        SecurityUtils.getSubject().login(new JWTToken(token));
        return ResultUtils.genSuccessResult(token);
    }

    @PostMapping("/id")
    public Result get(@RequestParam("id") Long id) {
        return ResultUtils.genSuccessResult(userService.findById(id));
    }

    @PostMapping("/name")
    public Result get(@RequestParam("name") String name) {
        return ResultUtils.genSuccessResult(userService.findByUsername(name));
    }

    @GetMapping("/list")
    public Result list() {
        return ResultUtils.genSuccessResult(userService.findList());
    }

    @PostMapping("/add")
    public Result add(@Valid UserDTO us) {
        //检验字段是否完整
//        if (bindingResult.hasErrors()) {
//            throw new BizException(bindingResult.getFieldError().getDefaultMessage());
//        }
        String salt = JWTUtils.getSalt();
        Md5Hash md5Hash = new Md5Hash(us.getPassword(), salt, 100);
        User user = new User();
        BeanUtils.copyProperties(us, user);
        user.setSalt(salt);
        user.setPassword(md5Hash.toHex());
        user.setCreatTime(new Date());
        userService.add(user);
        return ResultUtils.genSuccessResult();
    }

    @PutMapping("/update")
    public Result update(@Valid UserDTO user) {
        User us = userService.findByUsername(user.getUsername());
        if (us == null) {
            throw new BizException("用户不存在");
        }
        Md5Hash md5Hash = new Md5Hash(user.getPassword(), us.getSalt(), 100);
        us.setPassword(md5Hash.toHex());
        userService.update(us);
        return ResultUtils.genSuccessResult();
    }

    @DeleteMapping("/delete/{id}")
    public Result delete(@PathVariable Long id) {
        userService.deleteById(id);
        return ResultUtils.genSuccessResult();
    }
}
